//package com.zny.sescore.shiro;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.palmdoctor.mb.base.constant.AuditStatusEnum2;
//import com.palmdoctor.mb.base.constant.UserTypeEnum;
//import com.palmdoctor.mb.base.entity.*;
//import com.palmdoctor.mb.base.exception.BizException;
//import com.palmdoctor.mb.base.exception.MessageEnum;
//import com.palmdoctor.mb.base.model.LoginInfo;
//import com.palmdoctor.mb.base.util.StringUtils;
//import com.palmdoctor.mb.server.department.service.DepartmentDiseaseService;
//import com.palmdoctor.mb.server.department.service.DepartmentService;
//import com.palmdoctor.mb.server.system.service.SystemInfoService;
//import com.palmdoctor.mb.server.system.service.SystemUserService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.shiro.authc.AuthenticationException;
//import org.apache.shiro.authc.AuthenticationInfo;
//import org.apache.shiro.authc.AuthenticationToken;
//import org.apache.shiro.authc.SimpleAuthenticationInfo;
//import org.apache.shiro.authz.AuthorizationInfo;
//import org.apache.shiro.authz.SimpleAuthorizationInfo;
//import org.apache.shiro.realm.AuthorizingRealm;
//import org.apache.shiro.subject.PrincipalCollection;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Set;
//import java.util.stream.Collectors;
//
///**
// * 自定义Realm，处理认证和权限
// *
// * @author zhangnayi
// * @date 2021-03-28 14:58
// */
//@Slf4j
//@Component
//public class ShiroRealm extends AuthorizingRealm {
//
//    @Autowired
//    private SystemInfoService systemInfoService;
//
//    @Autowired
//    private SystemUserService systemUserService;
//
//    @Autowired
//    private DepartmentService departmentService;
//
//    @Autowired
//    private DepartmentDiseaseService departmentDiseaseService;
//
//    @Value("${global-setting.hospital-id}")
//    private Integer defaultHospitalId;
//
//    @Value("${his-setting.dialysis-disease-id}")
//    private Integer dialysisDiseaseId;
//
//    /**
//     * 权限处理
//     *
//     * @author zhangnayi
//     * @date 2021-03-27 18:56
//     */
//    @Override
//    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        LoginInfo loginInfo = (LoginInfo) principalCollection.getPrimaryPrincipal();
//        // 查询用户角色
//        List<SystemRole> roles = systemUserService.getUserRoleByUserId(loginInfo.getUserId());
//        List<String> roleCodes = new ArrayList<>();
//        for (SystemRole role : roles) {
//            roleCodes.add(role.getRoleCode());
//        }
//        // 查询用户权限
//        List<SystemPermission> permissions = getUserPermissionByUserId(loginInfo.getUserId());
//        List<String> permissionCodes = new ArrayList<>();
//        for (SystemPermission permission : permissions) {
//            permissionCodes.add(permission.getPermissionCode());
//        }
//        // 设置用户角色和权限
//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        authorizationInfo.addRoles(roleCodes);
//        authorizationInfo.addStringPermissions(permissionCodes);
//        return authorizationInfo;
//    }
//
//    /**
//     * 认证处理
//     *
//     * @author zhangnayi
//     * @date 2021-03-27 18:57
//     */
//    @Override
//    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        // 获取用户名
//        String username = authenticationToken.getPrincipal().toString();
//        // 根据用户名查询用户对象
//        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SystemUser::getUserName, username)
//                .eq(SystemUser::getStatus, AuditStatusEnum2.PASS.getValue())
//                .in(SystemUser::getUserType, Arrays.asList(UserTypeEnum.ADMIN.getValue(), UserTypeEnum.BACKEND.getValue()));
//        SystemUser user = systemUserService.getOne(queryWrapper);
//        if (user == null) {
//            log.error("用户名{}不存在,登陆失败", username);
//            throw new BizException(MessageEnum.USER_NOT_EXIST);
//        }
//
//        SystemInfo systemInfo = null;
//        if (StringUtils.isNotEmpty(user.getSystemIds())) {
//            String[] systemIdList = user.getSystemIds().split(",");
//            if (systemIdList.length > 0) {
//                Integer loginSystemId;
//                final Integer lastSystemId = user.getLastSystemId();
//                if (lastSystemId != null && Arrays.asList(systemIdList).contains(lastSystemId)) {
//                    loginSystemId = lastSystemId;
//                } else {
//                    loginSystemId = Integer.valueOf(systemIdList[0]);
//                }
//                systemInfo = systemInfoService.getById(loginSystemId);
//            }
//        }
//
//        LoginInfo loginInfo = LoginInfo.from(user, getUserPermissionByUserId(user.getUserId()), systemInfo);
//        List<Department> departmentList = departmentService.getUserDepartmentList(user.getUserId());
//        loginInfo.setDepartmentIdList(departmentList.stream().map(Department::getDepartmentId).collect(Collectors.toList()));
//        List<DepartmentDisease> diseaseList = departmentDiseaseService.getDepartmentDiseaseByUserId(user.getUserId());
//        loginInfo.setDepartmentDiseaseIdList(diseaseList.stream().map(DepartmentDisease::getDiseaseId).collect(Collectors.toList()));
//
//        loginInfo.setHosArea(getHosAreaId(user.getHisDepartmentId()));
//        loginInfo.setCommunityUserFlag(!defaultHospitalId.equals(loginInfo.getHospitalId()));
//
//        Set<Integer> diseaseIdSet = diseaseList.stream().map(DepartmentDisease::getDiseaseId).collect(Collectors.toSet());
//        loginInfo.setDialysisFlag(diseaseIdSet.contains(dialysisDiseaseId));
//        // 验证用户
//        return new SimpleAuthenticationInfo(loginInfo, user.getPassword(), this.getName());
//    }
//
//    /**
//     * 获取优化权限
//     *
//     * @param userId
//     * @return
//     */
//    private List<SystemPermission> getUserPermissionByUserId(Integer userId) {
//        return systemUserService.getUserPermissionByUserId(userId);
//    }
//
//    private Integer getHosAreaId(Integer hisDepartmentId) {
//        Department department = departmentService.getById(hisDepartmentId);
//        if (department != null) {
//            return department.getParentId();
//        }
//        return null;
//    }
//}
